//201902104047周润恺
package cn.edu.sdjzu.xg.bysj.controller.basic;

import cn.edu.sdjzu.xg.bysj.domain.ApplicationForSupervisor;
import cn.edu.sdjzu.xg.bysj.domain.ApplicationForSupervisorEntry;
import cn.edu.sdjzu.xg.bysj.domain.Teacher;
import cn.edu.sdjzu.xg.bysj.service.ApplicationForSupervisorService;
import cn.edu.sdjzu.xg.bysj.service.StudentService;
import cn.edu.sdjzu.xg.bysj.service.TeacherService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import util.JSONUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.TreeSet;

@WebServlet("/applicationForSupervisor.ctl")
@Slf4j
public class ApplicationForSupervisorController extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();

        try {
            //获得请求的json数据
            String request_jsonStr = JSONUtil.getJSON(request);
            //解析为json对象
            JSONObject req_jsonObj = JSON.parseObject(request_jsonStr);
            //如果请求body为空,响应未收到请求
            if (req_jsonObj == null) {
                respMessage_jsonObj.put("message","未收到请求信息！");
                response.getWriter().println(respMessage_jsonObj);
                log.error("未收到请求信息");
                return;
            }
            //新建志愿对象用于储存解析完成的数据
            ApplicationForSupervisor applicationForSupervisor = new ApplicationForSupervisor();
            //拿取自我介绍数据
            String selfIntroduction = req_jsonObj.get("selfIntroduction").toString();
            //拿取学生id
            int student_id = Integer.parseInt(req_jsonObj.get("student_id").toString());
            //拿取时间
            int year = Integer.parseInt(req_jsonObj.get("year").toString());

            //拿取储存志愿条目的jsonArray
            JSONArray entryList_jsonArray =
                    req_jsonObj.getJSONArray("applicationForSupervisorEntries");

            //新建集合用于储存解析完的志愿条目对象
            Collection<ApplicationForSupervisorEntry> applicationForSupervisorEntries = new TreeSet<>();

            log.trace("准备将jsonArray转为集合");
            for (int i = 0 ; i<entryList_jsonArray.size() ; i++){
                //获得jsonArray中的jsonObject（带有老师外键与志愿顺序）
                JSONObject obj = entryList_jsonArray.getJSONObject(i);
                //根据老师id查找老师
                Teacher teacher = TeacherService.getInstance().find(obj.getInteger("teacher_id"));
                //将解析出来的志愿条目对象添加进集合中
                applicationForSupervisorEntries.add(
                        new ApplicationForSupervisorEntry(teacher,obj.getInteger("priority")));
            }
            //为志愿对象设置解析出来的数据
            applicationForSupervisor.setApplicationForSupervisorEntries(applicationForSupervisorEntries);
            applicationForSupervisor.setSelfIntroduction(selfIntroduction);
            applicationForSupervisor.setStudent(StudentService.getInstance().find(student_id));
            applicationForSupervisor.setYear(year);
            log.trace(applicationForSupervisor.toString());
            //添加
            ApplicationForSupervisorService.getInstance().add(applicationForSupervisor);

            respMessage_jsonObj.put("message", "增加成功");
        } catch (SQLException e) {
            respMessage_jsonObj.put("message", "数据库操作异常");
            log.error("数据库操作异常" + e.getMessage());
        } catch (Exception e) {
            respMessage_jsonObj.put("message", "网络异常");
            log.error("网络异常" + e.getMessage());
        }
        finally {
            response.getWriter().println(respMessage_jsonObj);
        }
    }
}
